package com.lixin.web.netty;

import com.lixin.web.messageCodec.JsonMessageDecoder;
import com.lixin.web.messageCodec.JsonMessageEncode;
import com.lixin.web.netty.handler.UserManagementHandler;
import com.lixin.web.netty.handler.WebSocketAuthHandler;
import com.lixin.web.netty.handler.WebSocketExceptionHandler;
import com.lixin.web.netty.handler.WebSocketRequestHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Description:
 * Copyright:   Copyright (c)2023
 * Company:     sci
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2023-07-22 20:42:49
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2023-07-22     张李鑫                     1.0         1.0 Version
 */
@Component
@ChannelHandler.Sharable
public class WebSocketServerInitializer<T> extends ChannelInitializer<SocketChannel> {

    @Autowired
    private WebSocketRequestHandler webSocketRequestHandler;
    @Autowired
    private WebSocketAuthHandler webSocketAuthHandler;

    @Autowired
    private WebSocketExceptionHandler webSocketExceptionHandler;
    @Autowired
    private UserManagementHandler userManagementHandler;


    @Override
    protected void initChannel(SocketChannel ch) {

        ChannelPipeline pipeline = ch.pipeline();
        // 添加解码器和编码器
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast(new LengthFieldPrepender(4));
        pipeline.addLast(new JsonMessageEncode());
        pipeline.addLast(new JsonMessageDecoder());
        //心跳机制
        pipeline.addLast(new IdleStateHandler(3000, 0, 0));
        pipeline.addLast(userManagementHandler);

        // 添加自定义的处理器
        pipeline.addLast(webSocketAuthHandler);
        pipeline.addLast(webSocketRequestHandler);
        pipeline.addLast(webSocketExceptionHandler);
    }
}
